package utils

import (
	"encoding/json"
	"fmt"
	"github.com/vmihailenco/msgpack/v5"
	"strconv"
	"time"
	"xinduobang/stock/common/fisherrors"
)

func Abs(a int) int {
	if a < 0 {
		a *= -1
	}

	return a
}

func NowTime() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

func DeepCopy(src interface{}) (desc interface{}) {
	srcStr, err := msgpack.Marshal(src)
	if err != nil {
		return
	}
	err = msgpack.Unmarshal(srcStr, &desc)
	if err != nil {
		return
	}
	return
}

// 这里可以用上面的reflect来简写，但是效率会低，所以直接全部列出来了
func InterfaceToInt(t1 interface{}) (int, error) {
	//switch val.Kind() {
	//case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
	//result := val.Int()
	//fmt.Println(result)

	var t2 int
	var err error
	switch t1.(type) {
	case uint:
		t2 = int(t1.(uint))
	case int8:
		t2 = int(t1.(int8))
	case uint8:
		t2 = int(t1.(uint8))
	case int16:
		t2 = int(t1.(int16))
	case uint16:
		t2 = int(t1.(uint16))
	case int32:
		t2 = int(t1.(int32))
	case uint32:
		t2 = int(t1.(uint32))
	case int64:
		t2 = int(t1.(int64))
	case uint64:
		t2 = int(t1.(uint64))
	case float32:
		t2 = int(t1.(float32))
	case float64:
		t2 = int(t1.(float64))
	case string:
		t2, err = strconv.Atoi(t1.(string))
	case nil:
		t2 = 0
	case json.Number:
		t3, _ := t1.(json.Number).Int64()
		t2 = int(t3)
	default:
		t2 = t1.(int)
	}

	return t2, err
}

// fisherr 和 普通的err都能转换为字符串记录日志用
func GetErrorInfoForLog(e error) (errStr string) {
	if fishErr, ok := e.(*fisherrors.FishError); ok {
		return fishErr.ToString()
	} else {
		return fmt.Sprintf("err=%+v", e)
	}
}
